package com.material.c2c.classify.dao.datajpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import com.material.c2c.classify.model.ClassifyDTO;
/**
 * 查询
 * @author Administrator
 *
 */
public class JpaClassifyDaoImpl {
	private EntityManager entityManager;

	public JpaClassifyDaoImpl(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	Page<ClassifyDTO> findByPid(Pageable request,String pid,String key) {
		StringBuffer dataHql = new StringBuffer("select new com.material.c2c.classify.model.ClassifyDTO(")
				.append("spfl)");
		StringBuffer totalHql = new StringBuffer("select count(1)");
		StringBuffer paramHql = new StringBuffer("from SPFL spfl where 1=1");
		if(pid == null) {
			paramHql.append(" and spfl.pid is null");
		} else {
			paramHql.append(" and spfl.pid = :pid");
		}
		if(key != null && !"".equals(key)) {
			paramHql.append(" and spfl.flmc like :key");
		}
		dataHql.append(paramHql);
		totalHql.append(paramHql);
		Query dataQuery = entityManager.createQuery(dataHql.toString());
		Query totalQuery =entityManager.createQuery(totalHql.toString());
		if(pid != null) {
			dataQuery.setParameter("pid", pid);
			totalQuery.setParameter("pid", pid);
		}
		if(key != null && !"".equals(key)) {
			dataQuery.setParameter("key","%"+key+"%");
			totalQuery.setParameter("key","%"+key+"%");
		}
		dataQuery.setFirstResult(request.getOffset());
		dataQuery.setMaxResults(request.getPageSize());
		@SuppressWarnings("unchecked")
		List<ClassifyDTO> data = dataQuery.getResultList();
		long total =totalQuery.getFirstResult();
		Page<ClassifyDTO> res = new PageImpl(data,request,total);
		return res;
	}
}
